package site.action;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.n3r.eql.EqlPage;

import site.annotations.LoginIgnoreMethod;
import site.annotations.LoginVerifyAction;
import site.config.CommonConfig;
import site.exception.MessageException;
import site.obj.YearsCounts;
import site.service.ValuationService;
import site.util.CommonUtils;
import site.util.UploadCommon;

import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.opensymphony.xwork2.ActionSupport;

@LoginVerifyAction
public class ValuationAction extends ActionSupport {

    private static final long serialVersionUID = 1L;
    private File pdf;
    private String pdfFileName;
    private String pdfContentType;
    private String title;
    private String description;
    private String uploadDir;
    private Map retMessage;
    private String evalId;
    private Map evalInfo;
    private Map evaluates = Maps.newHashMap();

    // 分页
    private String currentPage;
    EqlPage eqlPage = new EqlPage();

    private String evalDate;

    @Resource
    private ValuationService valuationService;

    @Action(value = "/valuation/list", results = { @Result(name = "success", type = "freemarker", location =
            "/pages/valuation/ValuationList.ftl") })
    public String list() {
        // 分页
        eqlPage.setPageRows(CommonConfig.PAGE_ROWS);
        eqlPage.setCurrentPage(1);
        if (!Strings.isNullOrEmpty(currentPage)) {
            eqlPage.setCurrentPage(Integer.parseInt(currentPage));
        }

        evaluates.put("evalInfo", valuationService.queryEvaluates(eqlPage));

        //分页需返回的数据
        evaluates.put("pageInfo", ImmutableMap.of("totalPages", eqlPage.getTotalPages(), "totalSize",
                eqlPage.getTotalRows(), "currentPage", eqlPage.getCurrentPage()));
        return SUCCESS;
    }

    @Action(value = "/valuation/add", results = { @Result(name = "success", type = "freemarker", location =
            "/pages/valuation/ValuationAdd.ftl") })
    public String add() {
        return SUCCESS;
    }

    @Action(value = "/valuation/edit", results = { @Result(name = "success", type = "freemarker", location =
            "/pages/valuation/ValuationEdit.ftl") })
    public String edit() {
        if (Strings.isNullOrEmpty(evalId)) {
            throw new MessageException("不存在的评价信息");
        }
        evalInfo = valuationService.queryEvaluate(evalId);
        return SUCCESS;
    }

    @Action(value = "/valuation/submit", results = {
            @Result(name = "success", type = "redirect", location = "/valuation/list") })
    public String addSubmit() {
        if (Strings.isNullOrEmpty(title)) {
            throw new MessageException("名称不能为空");
        }
        if (Strings.isNullOrEmpty(description)) {
            throw new MessageException("描述不能为空");
        }
        if (pdf == null || !pdf.exists()) {
            throw new MessageException("内容不能为空");
        }

        // pdf文件上传
        String fileName = pdfUpload();

        if (!valuationService.insertEvaluate(ImmutableMap.of("title", title, "description", description, "filePath",
                CommonConfig.UPLOAD_PATH + fileName))) {
            throw new MessageException("入库失败");
        }

        retMessage = ImmutableMap.of("code", "OK", "desc", "新增成功");

        return SUCCESS;
    }

    @Action(value = "/valuation/update", results = {
            @Result(name = "success", type = "redirect", location = "/valuation/list") })
    public String update() {
        if (Strings.isNullOrEmpty(title)) {
            throw new MessageException("名称不能为空");
        }
        if (Strings.isNullOrEmpty(description)) {
            throw new MessageException("描述不能为空");
        }
        String fileName = null;
        if (pdf != null && pdf.exists()) {
            // pdf文件上传
            fileName = pdfUpload();
        }

        Map inMap = Maps.newHashMap();
        inMap.put("evalId", evalId);
        inMap.put("title", title);
        inMap.put("description", description);
        if (!Strings.isNullOrEmpty(fileName)) {
            inMap.put("filePath", CommonConfig.UPLOAD_PATH + fileName);
        }
        if (!valuationService.updateEvaluate(inMap)) {
            throw new MessageException("入库失败");
        }

        retMessage = ImmutableMap.of("code", "OK", "desc", "更新成功");

        return SUCCESS;
    }

    private String pdfUpload() {
        if (!"application/pdf".equals(pdfContentType)) {
            throw new MessageException("文件格式错误");
        }
        String fileName = UploadCommon.getRanString() + ".pdf";
        uploadDir = CommonUtils.getImgUploadPath() + fileName;
        File tempFile = new File(uploadDir);
        try {
            FileUtils.copyFile(pdf, tempFile);
        } catch (IOException e) {
            throw new MessageException("文件上传失败");
        }
        return fileName;
    }

    @Action(value = "/valuation/del", results = { @Result(name = "success", type = "json", params = { "root",
            "retMessage" }) })
    public String del() {
        if (Strings.isNullOrEmpty(evalId)) {
            throw new MessageException("ID不能为空");
        }
        if (!valuationService.delEvaluate(evalId)) {
            throw new MessageException("删除失败");
        }
        retMessage = ImmutableMap.of("code", "OK", "desc", "删除成功");
        return SUCCESS;
    }

    @LoginIgnoreMethod
    @Action(value = "/valuation", results = { @Result(name = "success", type = "freemarker", location = "/pages/valuation/Valuation.ftl") })
    public String evaluateInit() {
        List<YearsCounts> evalYears = valuationService.queryEvalYears();
        List<Map> evalList = Lists.newArrayList();
        if (evalYears.size() > 0) {
            eqlPage.setPageRows(CommonConfig.PAGE_ROWS);
            eqlPage.setCurrentPage(1);
            evalList = valuationService.queryEvalList(evalYears.get(0).getCreateYear(), eqlPage);
        }
        evalInfo = ImmutableMap.of("evalYears", evalYears, "evalList", evalList, "totalPages", eqlPage.getTotalPages(),
                "currentPage", eqlPage.getCurrentPage());
        return SUCCESS;
    }

    @LoginIgnoreMethod
    @Action(value = "/queryEvalList", results = { @Result(name = "success", type = "freemarker", location = "/pages/valuation/DateTab.ftl") })
    public String queryEvalList() {
        eqlPage.setPageRows(CommonConfig.PAGE_ROWS);
        eqlPage.setCurrentPage(1);
        if (!Strings.isNullOrEmpty(currentPage)) {
            eqlPage.setCurrentPage(Integer.parseInt(currentPage));
        }
        List<Map> evalList = Lists.newArrayList();
        if (!Strings.isNullOrEmpty(evalDate)) {
            evalList = valuationService.queryEvalList(evalDate, eqlPage);
        }
        evalInfo = ImmutableMap.of("evalList", evalList, "totalPages", eqlPage.getTotalPages(), "currentPage",
                eqlPage.getCurrentPage());
        return SUCCESS;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getUploadDir() {
        return uploadDir;
    }

    public void setUploadDir(String uploadDir) {
        this.uploadDir = uploadDir;
    }

    public File getPdf() {
        return pdf;
    }

    public void setPdf(File pdf) {
        this.pdf = pdf;
    }

    public String getPdfFileName() {
        return pdfFileName;
    }

    public void setPdfFileName(String pdfFileName) {
        this.pdfFileName = pdfFileName;
    }

    public String getPdfContentType() {
        return pdfContentType;
    }

    public void setPdfContentType(String pdfContentType) {
        this.pdfContentType = pdfContentType;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getEvalId() {
        return evalId;
    }

    public void setEvalId(String evalId) {
        this.evalId = evalId;
    }

    public Map getEvalInfo() {
        return evalInfo;
    }

    public void setEvalInfo(Map evalInfo) {
        this.evalInfo = evalInfo;
    }

    public Map getRetMessage() {
        return retMessage;
    }

    public void setRetMessage(Map retMessage) {
        this.retMessage = retMessage;
    }

    public Map getEvaluates() {
        return evaluates;
    }

    public void setEvaluates(Map evaluates) {
        this.evaluates = evaluates;
    }

    public String getCurrentPage() {
        return currentPage;
    }

    public void setCurrentPage(String currentPage) {
        this.currentPage = currentPage;
    }

    public String getEvalDate() {
        return evalDate;
    }

    public void setEvalDate(String evalDate) {
        this.evalDate = evalDate;
    }
}
